function [price,outRate]=shark_MC(S0,K,B,r,Sigma,T,Ntraj,Nstep)
%%%%%%%%%%%%%函数说明%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%传统蒙特卡罗方法计算鲨鱼鳍产品价格%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%输入参数：
%%%%%%%%%%S0：标的初始价格；K：期权执行价格；B：障碍水平；r：无风险利率；
%%%%%%%%%%Sigma：标的波动率；T：到期时间；
%%%%%%%%%%Ntraj：模拟路径数；Nstep：每条路径一年的时间分割数
%%%%%%%%%%输出参数：
%%%%%%%%%%Price:向上敲出看涨鲨鱼鳍产品价格;outRate=敲出路径所占比例
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PricePath=simuPath(S0,T,r,Sigma,Ntraj,Nstep)
pricepath=simuPath(S0,T,r,Sigma,Ntraj,Nstep);%一列为一条价格路径
outORnot=pricepath>B;%检验节点价格是否出现敲出
outPath=find(any(outORnot,1));%找到被敲出的路径索引
remPath=setdiff([1:Ntraj],outPath);%找到未敲出路径索引
payoff=zeros(1,Ntraj);%为所有路径到期日回报预分配内存
payoff(outPath)=0;%敲出路径收益为0
payoff(remPath)=max(pricepath(end,remPath)-K,0);%未敲出路径收益计算
price=exp(-r*T)*mean(payoff);%计算所有路径收益均值并进行贴现
outRate=length(outPath)/Ntraj;
end

%%%%%%%%%%%%%%%%%%%%%%%%%shark_MC函数中用于产生价格路径的函数%%%%%%%%%%%%%%%%%
function PricePath=simuPath(S0,T,r,Sigma,Ntraj,Nstep)
%%%%%%%%%%%%%%%%%%%%%%%函数说明%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%用途：产生服从几何布朗运动的标的资产价格路径
%%%%%%%%%%输入参数：
%%%%%%%%%%S0：标的初始价格；T：到期时间；r：无风险利率；Sigma：标的波动率；
%%%%%%%%%%Ntraj：模拟路径数；Nstep：每条路径一年的时间分割数
%%%%%%%%%%输出参数：
%%%%%%%%%%PricePath：Ntraj条标的资产的价格路径

%%%%%%%%%%%%%%%%%%%%%示例%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if (nargin<1)
T=1;S0=1; r=0.03; Sigma=0.13; 
Ntraj=10000; Nstep=200;
else
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%det(lnS)=(r-Sigma^2/2 )*deltaT+Sigma*sqrt(deltaT)*randn
deltaT=1/Nstep;
nStep=T/deltaT;
%%计算增量
mu=(r-Sigma^2/2 )*deltaT;
sigmadelta=Sigma*sqrt(deltaT);
Increments=mu+sigmadelta.*randn(nStep,Ntraj); %增量
% 计算对数价格
LogPrice=cumsum([log(S0)*ones(1,Ntraj); Increments]); 
%计算价格
PricePath=exp(LogPrice);%每一列是一次模拟的价格路径

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%价格路径可视化%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%plot(PricePath)
%title('Simulation of Price Path')
%ylabel('Asset Price');
%xlabel('Time Step');
%xlim([0,nStep]);
end

